﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

/*
 * 
 * Revision History
 * 
 * Date             Author          Modification
 * ----------       ----------      ----------
 * 10/03/2011       Paul Liebrand   Modified to be able to accept a custom name.
 *
 */

namespace Liebrand.UrlShortener
{
    public static class URLShortener
    {

        public static string GenerateShortUrl(SPList list, int itemId)
        {
            return GenerateShortUrl(list, itemId, string.Empty);

        }

        public static string GenerateShortUrl(SPList list, int itemId, string shortName)
        {
            try
            {
                var item = list.GetItemById(itemId);
                var itemUrl = string.Empty;

                if (item.File == null)
                    itemUrl = SPContext.Current.Web.Url + "/" + list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + item.ID;
                else
                    itemUrl = SPContext.Current.Web.Url + "/" + item.Url;

                var generatedShortedUrl = GenerateShortUrl(itemUrl, shortName);

                return generatedShortedUrl;
            }
            catch (Exception ex)
            {
                Utilities.WriteError(ex.ToString());

                throw new SPException("An error occurred while attempting to shorten a URL.", ex);
            }
        }

        public static string GenerateShortUrl(string longUrl)
        {
            return GenerateShortUrl(longUrl, String.Empty);
        }

        public static string GenerateShortUrl(string itemUrl, string shortName)
        {
            if (string.IsNullOrEmpty(shortName))
                shortName = Utilities.GenerateHash(itemUrl);

            var shortenerUrl = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                    var farm = SPAdministrationWebApplication.Local;
                    using (var site = farm.Sites[0])
                    {
                        using (var web = site.RootWeb)
                        {
                            if (!web.Properties.ContainsKey("LiebrandUrlShortener"))
                                throw new SPException(SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,CannotFindUrl", "liebrandurlshortener", web.Language));

                            var urlList = web.Lists[SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageName", "liebrandurlshortener", web.Language)];

                            var query = new SPQuery();
                            query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + shortName + "</Value></Eq></Where>";

                            var items = urlList.GetItems(query);
                            if (items.Count == 0)
                            {

                                var urlListItem = urlList.Items.Add();
                                urlListItem["Title"] = shortName;
                                urlListItem["RedirectTo"] = itemUrl;

                                web.AllowUnsafeUpdates = true;
                                urlListItem.Update();
                                web.AllowUnsafeUpdates = false;

                            }

                            shortenerUrl = web.Properties["LiebrandUrlShortener"];
                        }
                    }
            });

            return shortenerUrl + "/" + shortName;
        }

        public static bool DoesCustomNameExist(string customName)
        {
            var returnValue = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                var farm = SPAdministrationWebApplication.Local;
                using (var site = farm.Sites[0])
                {
                    using (var web = site.RootWeb)
                    {
                        if (!web.Properties.ContainsKey("LiebrandUrlShortener"))
                            throw new SPException(SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,CannotFindUrl", "liebrandurlshortener", web.Language));

                        var urlList = web.Lists[SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageName", "liebrandurlshortener", web.Language)];

                        var query = new SPQuery();
                        query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + customName + "</Value></Eq></Where>";

                        var items = urlList.GetItems(query);
                        if (items.Count > 0)
                        {

                            returnValue = true; 

                        }
                    }
                }
            });

            return returnValue;
        }

    }
}
